/*************************************************************************
	> File Name: 2.client.c
	> Author: Maureen 
	> Mail: 1437867946@qq.com 
	> Created Time: Sun 09 May 2021 12:55:25 PM CST
 ************************************************************************/

#include "head.h"

// ./client 123.57.102.65 20001

struct Packet {
    char filename[50];
    ssize_t size;
    char body[1024];
};

int send_file(int sockfd, const char *file) {
    //打开文件 两种模式：标准IO(fopen fread) , 普通IO(open read)
    FILE *fp;
    char *p;
    struct Packet packet;
    memset(&packet, 0, sizeof(packet));
    //strcpy(packet.filename, file);
    strcpy(packet.filename, (p = strrchr(file, '/')) ? p + 1 : file); //方便在本地测试
    if ((fp = fopen(file, "r")) == NULL) {
        perror("fopen");
        return -1;
    }
    fseek(fp, 0, SEEK_END);
    packet.size = ftell(fp); //获取文件大小
    fseek(fp, 0, SEEK_SET);
    while (1) {
        //读出文件并发送
        ssize_t nread = fread(packet.body, 1, sizeof(packet.body), fp);
        if (nread <= 0) {
            break;
        }
        //TODO: 存在一个bug，需要一个buffer，当读满body后再发送
        send(sockfd, (void *)&packet, sizeof(packet), 0);
        memset(packet.body, 0, sizeof(packet.body));
    }
    fclose(fp);
    return 0;
}

int main(int argc, char **argv) {
    if (argc != 4) {
        fprintf(stderr, "Usage : %s ip port file\n", argv[0]);
        exit(1);
    }

    int sockfd, port, ack;
    char ip[20] = {0}, file[50] = {0};
    strcpy(ip, argv[1]);
    port = atoi(argv[2]);
    strcpy(file, argv[3]);

    if ((sockfd = socket_connect(ip, port)) < 0) {
        perror("socket_connect");
        exit(1);
    }
    send(sockfd, "Maureen", sizeof("Maureen"), 0); //发送名称
    int rsize = recv(sockfd, (void *)&ack, sizeof(int), 0); //接收ack
    if (rsize <= 0 || ack != 1) {
        close(sockfd);
        exit(1);
    }
    printf("Waiting for data transfer!\n");

    send_file(sockfd, file);
    close(sockfd);
    return 0;
}

